package com.ojoin.trade.common_core.web.service.impl;

import java.util.List;
import java.util.Map;

import com.ojoin.trade.common.utils.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.common_core.web.dao.TbMerchantInfoDao;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfoCheck;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;

/**
 * Created with IntelliJ IDEA. User: Administrator Date: 15-11-17 Time: 上午10:29
 * To change this template use File | Settings | File Templates.
 */
@Service
public class TbMerchantInfoBaseServiceImpl extends
		BaseServiceImpl<TbMerchantInfo> implements TbMerchantInfoBaseService {
	@Autowired
	private TbMerchantInfoDao tbMerchantInfoDao;
	@Autowired
	private DataVersionValidationService validationService;

	@Autowired
	private TbMerchantInfoCheckServiceImpl checkService;

	@Autowired
	private MerchantUserBaseService userService;

	@Override
	protected BaseDao<TbMerchantInfo> getBaseDao() {
		return tbMerchantInfoDao;
	}

	@Override
	public int addTbMerchantInfo(TbMerchantInfo info) throws BusinessException {
		TbMerchantInfo dbMerchant = this.queryInfoByJoinId(info
				.getIdOfTbMerchantUser());
		if (null == dbMerchant) {
			getBaseDao().insert(info);
		} else {
			info.setId(dbMerchant.getId());
			((TbMerchantInfoDao) getBaseDao()).updateBySelective(info);
		}
		return info.getId();
	}

	@Override
	public void updateTbMerchantInfoBySelective(TbMerchantInfo info)
			throws BusinessException {
		((TbMerchantInfoDao) getBaseDao()).updateBySelective(info);
	}

	@Override
	public void updateTbMerchentInfoByVo(TbMerchantInfo info)
			throws BusinessException {
		String ts = TimeUtils.getDateString(info.getRowUpdateTime());
		int id = info.getId();
		validationService.validateVO(id, new TbMerchantInfo().getTableName(),
				ts);
		((TbMerchantInfoDao) getBaseDao()).updateById(info);
	}

	@Override
	public TbMerchantInfo queryInfoByJoinId(int joinid)
			throws BusinessException {
		return ((TbMerchantInfoDao) getBaseDao()).queryInfoByJoinid(joinid);
	}

	@Override
	public List<TbMerchantInfo> queryAllTbMerchantInfo(Pageable page)
			throws BusinessException {
		return ((TbMerchantInfoDao) getBaseDao()).queryAllInfo(page);
	}

	@Override
	public TbMerchantInfo selectRealnameInfoByJoinid(int joinid)
			throws BusinessException {
		return ((TbMerchantInfoDao) getBaseDao())
				.selectRealnameInfoByJoinid(joinid);
	}

	@Override
	public void pushRealInfoByJoinuserId(int joinuserid, int realStatus)
			throws BusinessException {
		if (realStatus == 2) {
			TbMerchantInfo infovo = ((TbMerchantInfoDao) getBaseDao())
					.selectRealnameInfoByJoinid(joinuserid);
			TbMerchantInfoCheck checkvo = checkService
					.selectByJoinuserId(joinuserid);
			if (infovo.getDoctype().equals("5")) {
				if (checkvo == null || checkvo.getYyzzCheckFlag() == null
						|| checkvo.getYyzzCheckFlag().intValue() == 0
						|| checkvo.getZzjgdmCheckFlag() == null
						|| checkvo.getZzjgdmCheckFlag().intValue() == 0
						|| checkvo.getSwdjzCheckFlag() == null
						|| checkvo.getSwdjzCheckFlag().intValue() == 0
						|| checkvo.getKhhzdCheckFlag() == null
						|| checkvo.getKhhzdCheckFlag().intValue() == 0
						|| checkvo.getKhxkzCheckFlag() == null
						|| checkvo.getKhxkzCheckFlag().intValue() == 0
						|| checkvo.getFrsfzCheckFlag() == null
						|| checkvo.getFrsfzCheckFlag().intValue() == 0) {
					throw new BusinessException("该商户的证件未全部检验通过，不可操作.");
				}
			} else if (infovo.getDoctype().equals("3")) {
				if (checkvo == null || checkvo.getYyzzCheckFlag() == null
						|| checkvo.getYyzzCheckFlag().intValue() == 0
						|| checkvo.getKhhzdCheckFlag() == null
						|| checkvo.getKhhzdCheckFlag().intValue() == 0
						|| checkvo.getKhxkzCheckFlag() == null
						|| checkvo.getKhxkzCheckFlag().intValue() == 0
						|| checkvo.getFrsfzCheckFlag() == null
						|| checkvo.getFrsfzCheckFlag().intValue() == 0) {
					throw new BusinessException("该商户的证件未全部检验通过，不可操作.");
				}
			}
		}

		TbMerchantInfo infovo = this.queryInfoByJoinId(joinuserid);
		List list = userService.realNameEnterpriseByPayUserInfo(
				infovo.getMhtNo(), infovo.getMchName(), infovo.getMobile(),
				infovo.getName(), infovo.getCertNo(), infovo.getLicNo(),
				infovo.getTaxNo(), infovo.getCertDate().replaceAll("-", ""), infovo.getOpenNo(),
				infovo.getOrgNo(), infovo.getCardMobile(), infovo.getCardNo(),
				infovo.getCardProvince(), infovo.getCardCity(),
				infovo.getBranchNo());
		if (!CommonUtils.isSuccess(list)) {
			LogUtils.error(log,(String) CommonUtils.buildError(list).getMessage());
			throw new BusinessException("提交实名认证信息失败，请检查.");
		}

	}

	@Override
	public int updateMhtnoByJoinuserId(int joinuserid, String mhtno)
			throws BusinessException {
		return ((TbMerchantInfoDao) getBaseDao()).updateMhtnoByJoinuserId(
				joinuserid, mhtno);
	}

	private Logger log = LoggerFactory
			.getLogger(TbMerchantInfoBaseServiceImpl.class);

	@Override
	public void pushAndSyncRealName(int joinuserid) throws BusinessException {
		TbMerchantUser uservo = userService.queryById(joinuserid);
		List muserinfoList = userService.queryPayUserVOByID(uservo
				.getUserIdOfIPayNow());
		if (muserinfoList == null && muserinfoList.size() == 0) {
			this.pushRealInfoByJoinuserId(joinuserid, 2);
			log.info("joinuserid->" + joinuserid + " 在支付未查到实名信息，已进行推送操作.");
			return;
		}
		if (CommonUtils.isSuccess(muserinfoList)) {
			Map<String, String> data = (Map) muserinfoList.get(1);
			String result = data.get("mhtData");
			log.info("joinuserid->" + joinuserid + " mhtData->" + result);

			TbMerchantInfo muserinfo = JSONUtils.parseObject(result,
					TbMerchantInfo.class);
			muserinfo.formateDate();

			if (IConstDef.REALNAME_STATUS_PASS != CommonUtils.getInt(muserinfo
					.getRealStatus()))
				throw new BusinessException("用户" + joinuserid
						+ "的实名审核尚未通过，请通过后再进行同步操作.");

			muserinfo.setIdOfTbMerchantUser(joinuserid);

			TbMerchantInfo oldinfovo = queryInfoByJoinId(joinuserid);
			if (oldinfovo != null) {
				muserinfo.setId(oldinfovo.getId());
				muserinfo.setDoctype(oldinfovo.getDoctype());
				muserinfo.setAddress(oldinfovo.getAddress());
				this.getBaseDao().updateById(muserinfo);
			}else{
				this.getBaseDao().insert(muserinfo);
			}
			log.info("joinuserid->" + joinuserid + "审批通过的实名信息同步成功.");
		}
	}
	
	@Override
	public void syncRealName(int joinuserid) throws BusinessException {
		TbMerchantUser uservo = userService.queryById(joinuserid);
		List muserinfoList = userService.queryPayUserVOByID(uservo
				.getUserIdOfIPayNow());
		if (CommonUtils.isSuccess(muserinfoList)) {
			Map<String, String> data = (Map) muserinfoList.get(1);
			String result = data.get("mhtData");
			log.info("joinuserid->" + joinuserid + " mhtData->" + result);

			TbMerchantInfo muserinfo = JSONUtils.parseObject(result,
					TbMerchantInfo.class);
			muserinfo.formateDate();

			if (IConstDef.REALNAME_STATUS_INIT == CommonUtils.getInt(muserinfo.getRealStatus()) ||
				IConstDef.REALNAME_STATUS_APPLYING == CommonUtils.getInt(muserinfo.getRealStatus())) {
				throw new BusinessException("用户" + joinuserid
						+ "的实名申请还在审核中，请通过后再进行同步操作.");
			}
				
			if (IConstDef.REALNAME_STATUS_PASS == CommonUtils.getInt(muserinfo.getRealStatus()) || 
				IConstDef.REALNAME_STATUS_UNPASS == CommonUtils.getInt(muserinfo.getRealStatus())) {
				muserinfo.setIdOfTbMerchantUser(joinuserid);
	
				TbMerchantInfo oldinfovo = queryInfoByJoinId(joinuserid);
				if (oldinfovo != null) {
					muserinfo.setId(oldinfovo.getId());
					muserinfo.setDoctype(oldinfovo.getDoctype());
					muserinfo.setAddress(oldinfovo.getAddress());
					this.getBaseDao().updateById(muserinfo);
				}else{
					this.getBaseDao().insert(muserinfo);
				}
				log.info("joinuserid->" + joinuserid + "实名信息同步成功. 实名状态->" + muserinfo.getRealStatus());
			}
		}
	}

	@Override
	public List<TbMerchantInfo> queryByNameVague(String name) throws BusinessException {
		return tbMerchantInfoDao.queryByNameVague(name);

	}

	@Cacheable(value = "enumCache",key="#mhtno")
	@Override
	public TbMerchantInfo queryInfoByMhtno(String mhtno)
			throws BusinessException {
		return ((TbMerchantInfoDao) getBaseDao()).queryInfoByMhtno(mhtno);
	}
}
